<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js对象之属性</title>
</head>
<body>
  <ul>
    <li>对象可通过.或['']来动态添加新属性，使用delete来删除对应的属性</li>
    <li>对象可通过hasOwnProperty()检测自身包含的属性，通过in检测自身和原型链上的属性</li>
    <li>可将对象数组转化为对象(一般会使用reduce进行累积获得)</li>
    <li>可使用Object.assign()生成一个新的对象，也可用于参数合并(对象解构，默认值都可实现)</li>
    <li>可使用Object.keys()获取对象的键，Object.values()获取对象的值，Object.entries获取对象的键值对</li>
    <li>可使用for...in/of遍历keys和values，entries，其中for...in循环的是索引，for...of循环的是值</li>
  </ul>
  <script>
    const user1 = {}
    user1.name = 'Miracle'
    user1['age'] = 35
    console.log(user1)                           // {name: "Miracle", age: 35}
    delete user1.age
    // delete user['age']
    console.log(user1)                           // {name: "Miracle"}
    console.log(user1.hasOwnProperty('name'))    // true
    const git = { url: 'https://github.com/miracle-git' }
    Object.setPrototypeOf(user1, git)
    console.log(user1.hasOwnProperty('url'))     // false
    console.log('url' in user1)                  // true
    console.log('name' in user1)                 // true
    // 将对象数组转化为对象
    const blogs = [
      { url: 'https://github.com/miracle-git/vue', title: 'Vue' },
      { url: 'https://github.com/miracle-git/react', title: 'React' },
      { url: 'https://github.com/miracle-git/angular', title: 'Angular' }
    ]
    const res = blogs.reduce((res, item, index) => {
      const prop = `0${index + 1} - ${item['title'].toLowerCase()}`
      return { ...res, [prop]: item }
    }, {})
    console.log(JSON.stringify(res, null, 2))
    // 参数合并
    function upload(params) {
      const config = { type: '.jpg,.png', size: 2000 }
      const res = Object.assign({}, config, params)
      console.log(res)
    }
    upload()                                       // {type: ".jpg,.png", size: 2000}
    upload({ type: '.gif' })                       // {type: ".gif", size: 2000}
    const user2 = { name: 'Miracle', age: 35, web: 'https://github.com/miracle-git' }
    console.log(Object.keys(user2))                // ["name", "age", "web"]
    console.log(Object.values(user2))              // ["Miracle", 35, "https://github.com/miracle-git"]
    console.log(JSON.stringify(Object.entries(user2), null, 2))
    for (const key of Object.keys(user2)) {
      console.log(key)
    }
    for (const val of Object.values(user2)) {
      console.log(val)
    }
    for (const [key, val] of Object.entries(user2)) {
      console.log(key, val)
    }
  </script>
</body>
</html>